from flask import Flask, render_template, request, jsonify, Response, session, make_response
import os
from config import Config 
import secrets
import requests
import uuid

# app = Flask("程序名称", static_folder="静态文件目录", template_folder="模板文件目录")
app = Flask(__name__, template_folder='templates')

# 生成一个强随机的 secret_key
secret_key = secrets.token_hex(32)  # 生成 64 字符的十六进制密钥（32字节）

# 会话key
app.secret_key = os.getenv('FLASK_SECRET_KEY') if os.getenv('FLASK_SECRET_KEY') else secret_key

class DeepSeekChatbot:
     # 定义静态⽅法
    @staticmethod

    def get_response(user_message, conversation_history=None):

        if conversation_history is None:
            conversation_history = []

        # 请求地址
        url = Config.DEEPSEEK_BASE_URL

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {Config.DEEPSEEK_API_KEY}"
        }

        # 构建消息历史，包括新消息
        messages = conversation_history.copy()
        messages.append({"role": "user", "content": user_message})

        data = {
            "model": Config.DEEPSEEK_MODEL,
            "messages" : messages,
            "max_tokens": Config.MAX_TOKENS,
            "temperature": Config.TEMPERATURE
        }

        try:
            response = requests.post(url, headers=headers, json=data)
            result = response.json()
            return result['choices'][0]['message']['content']
    
        except requests.exceptions.RequestException as e:
            app.logger.error(f"DeepSeek API请求失败: {e}")
            return "抱歉，暂时无法连接到AI服务，请稍后再试。"

        except (KeyError, IndexError) as e:
            app.logger.error(f"解析DeepSeek响应失败: {e}")
            return "抱歉，处理AI响应时出现错误。"
        
@app.route('/')
def index():

    # 设置session  为每个会话创建唯一ID
    if 'name' not in session:
        session['session_id'] = str(uuid.uuid4())

    resp = make_response(render_template('index.html'))
    # 设置cookie
    # resp.set_cookie('username', 'admin')

    # 删除cookie，设置过期时间，值为空，
    # resp.set_cookie('username', '', expires=0)

    # 获取cookie
    # print(request.cookies.get('username'))

    # 删除session
    # session.pop('name', None)

    # 获取session
    # print(session.get('name'))

    
    return resp

    # return render_template('index.html')

@app.route('/login')
def login():
    return render_template('login.html')

@app.route('/subject/index')
def subjectindex():
    return render_template('subject/index.html')

@app.route('/chat', methods=['post'])
def chat():
    try:
        # 获取前端的传参
        data = request.get_json()
        # 去除字符串两端的空白字符  
        user_message = data.get('message', '').strip()
        conversation_history = data.get('history', [])

        # 判断消息是否为空
        if not user_message:
            return  jsonify({"response": "请输入内容~", "error": False})
      
        # 调取AI模型请求
        response = DeepSeekChatbot.get_response(user_message, conversation_history)

        return jsonify({
            "response": response,
            "error": False,
            "session_id": session.get('session_id')
        })
    except Exception as e:
        app.logger.error(f"聊天接口错误: {e}")
        return jsonify({
            "response": "抱歉，服务器处理请求时出现错误，请稍后再试。",
            "error": True
        }), 500

@app.route('/config', methods=['post'])
def config():
        """获取当前配置信息（不包含敏感信息）"""
        return jsonify({
            "model": Config.DEEPSEEK_MODEL,
            "base_url": Config.DEEPSEEK_BASE_URL,
            "temperature" : Config.TEMPERATURE,
        })

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)
